from rest_framework.views import APIView
from rest_framework import exceptions
from rest_framework import serializers
from rest_framework.authentication import BaseAuthentication
from rest_framework.pagination import CursorPagination, LimitOffsetPagination, PageNumberPagination
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser

import json
import time
import re
import cpca

from django.http import JsonResponse
from Shops.models import Shops_base
from Goods.models import GoodsBase, Goodspackage
from user.models import User_Account,User_Token,User_Information
from . import models


def get_order_code():
    order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(
        time.time()))) + str(time.time()).replace('.', '')[-7:]
    return order_no
def getUser(request):
    # 用户User_Account表的数据
    try:
        Token = request.META.get("HTTP_TOKEN")  # 获取用户token
        User = User_Token.objects.get(token=Token).user  # 获取用户对象
        return User
    except:
        print("token异常未登录时访问带TOKEN验证的接口 请记录此Ip")
        return False


class Order(APIView):
    # parser_classes = [FormParser, JSONParser, MultiPartParser]
    def post(self, request, *args, **kwargs):
        ret = {}

        # try:
        #     request.GET["desc"]
        # except:
        #     pass
        # addressData = request.GET["addressData"]
        desc = request.data['desc']
        # 需要的数据

        # 生成订单号+
        code = get_order_code()
        # 店铺
        store = request.data['store']
        storeObj = Shops_base.objects.get(id=1)
        # 收货人姓名+ # 省+  # 市+ # 区+  # 地址+
        addressData = json.loads(request.data['addressData'])
        location_str = []
        location_str.append(addressData['address'])
        df = cpca.transform(location_str, index=0)
        # 支付方式+
        # 订单金额+
        # 支付金额+

        # 运费金额
        # 快递公司名称
        # 快递单号
        dic = {
            "sn": code,
            "shipping_user": addressData['name'],
            "user": getUser(request),
            "contact": addressData['mobile'],
            "address": addressData['area'],
            "order_status": 1,
            "province": df.iloc[0, 0],
            "city": df.iloc[0, 1],
            "district": df.iloc[0, 2],
        }

        obj = models.OrderMaster.objects.create(**dic)
        # 匹配最近店铺
        # 创建订单商品
        goodsList = json.loads(request.data['list'])
        for i in goodsList:
            goods_Obj = Goodspackage.objects.get(id=i['GoodspackageID'])
            dic = {
                "order_id": obj,
                "goods_id": goods_Obj.Goods.GoodsBase,
                "goods_name": i['name'] + i['typename'],
                "product_num": i['num'],
                "product_price": goods_Obj.price
            }
            models.orderDetail.objects.create(**dic)
            print(dic)
        ret['state'] = 2000
        ret['code'] = code
        return JsonResponse(ret)

    def get(self, request, *args, **kwargs):
        ret = {}
        user = getUser(request)
        orderList = models.OrderMaster.objects.filter(user=user)
        List = ShoppingCartSer(
            instance=orderList, many=True).data  # 序列化 获取到相关数据
        return JsonResponse(List,safe=False)

    # def post(self, request, *args, **kwargs):
    # def post(self, request, *args, **kwargs):
class ShoppingCartSer(serializers.ModelSerializer):
    time = serializers.DateTimeField(source="create_time",format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    state = serializers.IntegerField(source="order_status")
    goodsList = serializers.SerializerMethodField()
    def get_goodsList(self,obj):
        ret = []
        e = models.orderDetail.objects.filter(order_id=obj.id)
        if len(e)>1:
            for item in e:
                ret.append({'image':item.src})
        elif len(e) == 1:
            ret.append({
                'title':e[0].goods_name,
                'price':e[0].product_price,
                'image':e[0].src,
                'number':e[0].product_num,
                'attr':e[0].attr,
                })
        return ret

    class Meta:
        model = models.OrderMaster
        fields = ['id','time','state','goodsList','payment_money']
